﻿using Engine.Graphics;
using Engine;
using GameEntitySystem;
using System;
using System.Collections.Generic;
using TemplatesDatabase;

namespace CommandBlock
{
    /// <summary>
    /// 命令辅助棒行为
    /// </summary>
    public class SubsystemCmdRodBlockBehavior : SubsystemBlockBehavior, IDrawable, IUpdateable
    {
        public class CommandPointData
        {
            public string Pos;

            public string Value;

            public bool Lock;

            public BevelledButtonWidget Button;
        }

        public override int[] HandledBlocks => [BlocksManager.GetBlockIndex("CmdRodBlock")];

        public SubsystemTerrain m_subsystemTerrain;

        public SubsystemPickables m_subsystemPickables;

        public SubsystemProjectiles m_subsystemProjectiles;

        public SubsystemCommand m_subsystemCommand;

        public SubsystemTime m_subsystemTime;

        public PrimitivesRenderer3D m_primitivesRenderer3D = new PrimitivesRenderer3D();

        public PrimitivesRenderer3D m_primitivesRenderer3D2 = new PrimitivesRenderer3D();

        public Point3? m_recordPosition;

        public int? m_recordBlockValue;

        public Point2? m_recordEyes;

        public int? m_recordfurnitureId;

        public int? m_recordclothesId;

        public string m_recordEntityName = null;

        public string m_commandLine = string.Empty;

        private Color m_color = Color.Yellow;

        private float m_lastGameTime;

        private float m_aimTime;

        private bool m_firstAim = true;

        private Vector3 m_targetPos;

        private Texture2D m_texture;

        private Color m_sightColor;

        public static bool QuickMode = false;

        public int m_pointIndex;

        public StackPanelWidget m_pointDataWidget;

        public BitmapButtonWidget m_withdrawButton;

        public BitmapButtonWidget m_recoveryButton;

        public Dictionary<string, CommandPointData> m_commandPoints = new Dictionary<string, CommandPointData>();

        public static bool ShowRay = true;

        public static bool ShowChunk = false;

        public int[] DrawOrders => new int[1] { 200 };

        public UpdateOrder UpdateOrder => UpdateOrder.Default;

        public void Draw(Camera camera, int drawOrder)
        {
            if (m_subsystemCommand.m_componentPlayer == null) return;
            if (m_targetPos != Vector3.Zero)
            {
                float s = 2f;
                Vector3 playerPos = m_subsystemCommand.m_componentPlayer.ComponentCreatureModel.EyePosition;
                Vector3 direction = Vector3.Normalize(m_targetPos - playerPos);
                Vector3 v = playerPos + direction * 50f;
                var vector = Vector3.Normalize(Vector3.Cross(direction, Vector3.UnitY));
                var v2 = Vector3.Normalize(Vector3.Cross(direction, vector));
                Vector3 p = v + s * (-vector - v2);
                Vector3 p2 = v + s * (vector - v2);
                Vector3 p3 = v + s * (vector + v2);
                Vector3 p4 = v + s * (-vector + v2);
                TexturedBatch3D texturedBatch3D = m_primitivesRenderer3D.TexturedBatch(m_texture, useAlphaTest: false, 0, DepthStencilState.None);
                int count = texturedBatch3D.TriangleVertices.Count;
                texturedBatch3D.QueueQuad(p, p2, p3, p4, new Vector2(0f, 0f), new Vector2(1f, 0f), new Vector2(1f, 1f), new Vector2(0f, 1f), m_sightColor);
                texturedBatch3D.TransformTriangles(camera.ViewMatrix, count);
                m_primitivesRenderer3D.Flush(camera.ProjectionMatrix);
            }
            else
            {
                m_primitivesRenderer3D.Clear();
            }
            if (m_recordPosition.HasValue)
            {
                Vector3 v = new Vector3(m_recordPosition.Value);
                FlatBatch3D flatBatch3D = m_primitivesRenderer3D2.FlatBatch();
                BoundingBox boundingBox = new BoundingBox(v, v + new Vector3(1f));
                Color color = Color.Green;
                if (ShowRay)
                {
                    flatBatch3D.QueueLine(v + new Vector3(-100.5f, 0.5f, 0.5f), v + new Vector3(100.5f, 0.5f, 0.5f), Color.Yellow);
                    flatBatch3D.QueueLine(v + new Vector3(0.5f, -100.5f, 0.5f), v + new Vector3(0.5f, 100.5f, 0.5f), color);
                    flatBatch3D.QueueLine(v + new Vector3(0.5f, 0.5f, -100.5f), v + new Vector3(0.5f, 0.5f, 100.5f), color);
                }
                flatBatch3D.QueueBoundingBox(boundingBox, color);
                flatBatch3D.QueueLine(v + new Vector3(1f, 0, 0), v + new Vector3(0.9f, 0, 0.05f), Color.Yellow);
                flatBatch3D.QueueLine(v + new Vector3(1f, 0, 0), v + new Vector3(0.9f, 0, -0.05f), Color.Yellow);
                flatBatch3D.QueueLine(v + new Vector3(0f, 1f, 0), v + new Vector3(0.05f, 0.9f, 0), color);
                flatBatch3D.QueueLine(v + new Vector3(0f, 1f, 0), v + new Vector3(-0.05f, 0.9f, 0), color);
                flatBatch3D.QueueLine(v + new Vector3(0f, 0, 1f), v + new Vector3(0.05f, 0, 0.9f), color);
                flatBatch3D.QueueLine(v + new Vector3(0f, 0, 1f), v + new Vector3(-0.05f, 0, 0.9f), color);
                if (ShowChunk)
                {
                    Color color2 = Color.Blue;
                    Point2 coord = Terrain.ToChunk(new Vector2(v.X, v.Z));
                    Vector3 origin = new Vector3(coord.X * 16, 0, coord.Y * 16);
                    flatBatch3D.QueueLine(origin, origin + new Vector3(0, 255, 0), color2);
                    flatBatch3D.QueueLine(origin + new Vector3(0, 0, 16), origin + new Vector3(0, 255, 16), color2);
                    flatBatch3D.QueueLine(origin + new Vector3(16, 0, 0), origin + new Vector3(16, 255, 0), color2);
                    flatBatch3D.QueueLine(origin + new Vector3(16, 0, 16), origin + new Vector3(16, 255, 16), color2);
                }
                m_primitivesRenderer3D2.Flush(camera.ViewProjectionMatrix);
            }
            else
            {
                m_primitivesRenderer3D2.Clear();
            }
        }

        public override bool OnAim(Ray3 aim, ComponentMiner componentMiner, AimState state)
        {
            if (m_firstAim)
            {
                m_lastGameTime = (float)m_subsystemTime.GameTime;
                m_aimTime = 0;
                m_firstAim = false;
                m_targetPos = Vector3.Zero;
                m_sightColor = Color.Red;
            }
            if (state == AimState.InProgress)
            {
                m_aimTime = (float)m_subsystemTime.GameTime - m_lastGameTime;
                if (m_aimTime > 1f)
                {
                    object result = DataHandle.Raycast(aim, componentMiner);
                    if (result is TerrainRaycastResult)
                    {
                        CellFace cellFace = ((TerrainRaycastResult)result).CellFace;
                        m_targetPos = new Vector3(cellFace.Point) + new Vector3(0.5f) - aim.Direction * 2f;
                        m_sightColor = Color.Green;
                    }
                    else if (result is BodyRaycastResult)
                    {
                        ComponentBody componentBody = ((BodyRaycastResult)result).ComponentBody;
                        m_targetPos = componentBody.Position - aim.Direction * 2f;
                        m_sightColor = Color.Green;
                    }
                    else if (result is Ray3)
                    {
                        Ray3 ray = (Ray3)result;
                        m_targetPos = ray.Position + ray.Direction * 100;
                        m_sightColor = Color.Red;
                    }
                }
            }
            else if (state == AimState.Completed)
            {
                m_firstAim = true;
                if (m_sightColor != Color.Red)
                {
                    componentMiner.ComponentPlayer.ComponentBody.Position = m_targetPos;
                    m_targetPos = Vector3.Zero;
                    m_sightColor = Color.Red;
                    return true;
                }
                else
                {
                    m_targetPos = Vector3.Zero;
                }
            }
            else if (state == AimState.Cancelled)
            {
                m_firstAim = true;
                m_targetPos = Vector3.Zero;
            }
            return false;
        }

        public override bool OnUse(Ray3 ray, ComponentMiner componentMiner)
        {
            object result = componentMiner.Raycast(ray, RaycastMode.Digging);
            Point2 playerEyes = DataHandle.GetPlayerEyesAngle(componentMiner.ComponentPlayer);
            //Point2 cameraEyes = DataHandle.DirectionToEyes(componentMiner.ComponentPlayer.PlayerData.GameWidget.ActiveCamera.ViewDirection);
            string eyesDebug = string.Format("\n视角: 水平方向:{0},垂直方向:{1}", playerEyes.X, playerEyes.Y);
            if (result is TerrainRaycastResult)
            {
                CellFace cellFace = ((TerrainRaycastResult)result).CellFace;
                int cellValue = m_subsystemTerrain.Terrain.GetCellValue(cellFace.X, cellFace.Y, cellFace.Z);
                int limitValue = Terrain.ReplaceLight(cellValue, 0);
                int id = Terrain.ExtractContents(cellValue);
                int data = Terrain.ExtractData(cellValue);
                int dropsValue = -1;
                foreach (Pickable pickable in m_subsystemPickables.Pickables)
                {
                    float distance = Vector3.Distance(pickable.Position, new Vector3(cellFace.Point));
                    if (distance <= 1.5f)
                    {
                        dropsValue = pickable.Value;
                        break;
                    }
                }
                string blockDebug = string.Empty;
                string furnitureDebug = string.Empty;
                string dropsDebug = string.Empty;
                blockDebug = string.Format("方块ID:{0}；特殊值:{1}；方块值:{2}\n标准坐标:({3},{4},{5})；方块面:{6}", id, data, limitValue, cellFace.X, cellFace.Y, cellFace.Z, cellFace.Face);
                if (id == CommandBlock.Index)
                {
                    componentMiner.ComponentPlayer.ComponentGui.DisplaySmallMessage(blockDebug, Color.LightBlue, false, false);
                    return false;
                }
                if (id == 227)
                {
                    int furnitureIndex = FurnitureBlock.GetDesignIndex(data);
                    int furnitureRotation = FurnitureBlock.GetRotation(data);
                    int furnitureFace = ((cellFace.Face - furnitureRotation) >= 0) ? (cellFace.Face - furnitureRotation) : (cellFace.Face - furnitureRotation + 4);
                    if (cellFace.Face == 4 || cellFace.Face == 5)
                    {
                        furnitureFace = cellFace.Face;
                    }
                    m_recordfurnitureId = furnitureIndex;
                    furnitureDebug = string.Format("\n家具序号:{0}；家具面:{1}", furnitureIndex, furnitureFace);
                }
                if (dropsValue != -1)
                {
                    int dropsId = Terrain.ExtractContents(dropsValue);
                    int dropsData = Terrain.ExtractData(dropsValue);
                    dropsDebug = string.Format("\n检测到掉落物的ID:{0}；特殊值:{1}；方块值:{2}", dropsId, dropsData, dropsValue);
                    if (dropsId == 203)
                    {
                        int clothId = ClothingBlock.GetClothingIndex(dropsData);
                        m_recordclothesId = clothId;
                        dropsDebug += "；衣物序号:" + clothId;
                    }
                }
                SetPointData(cellFace.Point);
                m_recordPosition = cellFace.Point;
                m_recordBlockValue = (dropsValue != -1) ? dropsValue : limitValue;
                m_recordEyes = playerEyes;
                componentMiner.ComponentPlayer.ComponentGui.DisplaySmallMessage(blockDebug + eyesDebug + furnitureDebug + dropsDebug, m_color, false, false);
                return true;
            }
            else if (result is BodyRaycastResult)
            {
                ComponentBody componentBody = ((BodyRaycastResult)result).ComponentBody;
                if (componentBody != null)
                {
                    string keyName = componentBody.Entity.ValuesDictionary.DatabaseObject.Name.ToLower();
                    ComponentCreature componentCreature = componentBody.Entity.FindComponent<ComponentCreature>();
                    ComponentDamage componentDamage = componentBody.Entity.FindComponent<ComponentDamage>();
                    string entityDebug = "生物实体名:" + keyName;
                    Point3 bodyPos = DataHandle.GetBodyPoint(componentBody);
                    if (componentCreature != null)
                    {
                        string displayName = componentCreature.DisplayName;
                        float health = componentCreature.ComponentHealth.Health * 100;
                        string mass = componentBody.Mass.ToString();
                        string boxSize = componentBody.BoxSize.ToString();
                        float flySpeed = componentCreature.ComponentLocomotion.FlySpeed;
                        float walkSpeed = componentCreature.ComponentLocomotion.WalkSpeed;
                        float jumpSpeed = componentCreature.ComponentLocomotion.JumpSpeed;
                        componentCreature.ComponentLocomotion.SwimSpeed.ToString();
                        entityDebug += string.Format("；名称:{0}；\n血量:{1}%；质量:{2}；\n位置:({3})；碰撞箱:{4}；", displayName, health, mass, bodyPos.ToString(), boxSize);
                        entityDebug += string.Format("\n飞行速度:{0}；行走速度:{1}；跳跃速度:{2}", MathUtils.Round(flySpeed * 10f) / 10f, MathUtils.Round(walkSpeed * 10f) / 10f, MathUtils.Round(jumpSpeed * 10f) / 10f);
                    }
                    else if (componentDamage != null)
                    {
                        float hitPoint = componentDamage.Hitpoints * 100;
                        float attackRes = componentDamage.AttackResilience;
                        string mass = componentBody.Mass.ToString();
                        string boxSize = componentBody.BoxSize.ToString();
                        entityDebug += string.Format("；血量:{0}%；\n攻击抗性:{1}；质量:{2}；\n位置:({3})；碰撞箱:{4}；", hitPoint, attackRes, mass, bodyPos.ToString(), boxSize);
                    }
                    SetPointData(bodyPos);
                    m_recordPosition = bodyPos;
                    m_recordEntityName = keyName;
                    componentMiner.ComponentPlayer.ComponentGui.DisplaySmallMessage(entityDebug, m_color, false, false);
                    return true;
                }
            }
            else if (result is MovingBlocksRaycastResult)
            {
                IMovingBlockSet movingBlockSet = ((MovingBlocksRaycastResult)result).MovingBlockSet;
                string moveDebug = (movingBlockSet.Tag != null) ? "该运动方块标签名为:" + movingBlockSet.Tag.ToString() : "该运动方块标签名不存在";
                moveDebug += "；所在位置:" + string.Format("({0})", movingBlockSet.Position.ToString());
                SetPointData(new Point3(movingBlockSet.Position));
                m_recordPosition = new Point3(movingBlockSet.Position);
                componentMiner.ComponentPlayer.ComponentGui.DisplaySmallMessage(moveDebug, m_color, false, false);
                return true;
            }
            else
            {
                Point3 playerPos = DataHandle.GetBodyPoint(componentMiner.ComponentPlayer.ComponentBody);
                SetPointData(playerPos);
                m_recordPosition = playerPos;
                m_recordEntityName = "player";
                m_recordEyes = playerEyes;
                componentMiner.ComponentPlayer.ComponentGui.DisplaySmallMessage(string.Format("玩家名:player; 玩家坐标:({0})", playerPos.ToString()) + eyesDebug, m_color, false, false);
            }
            return false;
        }

        public override bool OnEditInventoryItem(IInventory inventory, int slotIndex, ComponentPlayer componentPlayer)
        {
            if (componentPlayer.ComponentGui.ModalPanelWidget is CommandEditWidget)
            {
                CommandEditWidget commandEditWidget = (CommandEditWidget)componentPlayer.ComponentGui.ModalPanelWidget;
                commandEditWidget.ParentWidget.ClearChildren();
                CommandEditWidget.GuiWidgetControl(componentPlayer, true);
                componentPlayer.ComponentGui.ModalPanelWidget = null;
            }
            else
            {
                componentPlayer.ComponentGui.ModalPanelWidget = new CommandEditWidget(base.Project, componentPlayer, Point3.Zero, true);
            }
            return true;
        }

        public override void Load(ValuesDictionary valuesDictionary)
        {
            m_subsystemTerrain = base.Project.FindSubsystem<SubsystemTerrain>(true);
            m_subsystemPickables = base.Project.FindSubsystem<SubsystemPickables>(true);
            m_subsystemProjectiles = base.Project.FindSubsystem<SubsystemProjectiles>(true);
            m_subsystemCommand = base.Project.FindSubsystem<SubsystemCommand>(true);
            m_subsystemTime = base.Project.FindSubsystem<SubsystemTime>(true);
            m_texture = ContentManager.Get<Texture2D>("Textures/Gui/Sights");
            m_commandLine = valuesDictionary.GetValue<string>("CommandLine");
            m_pointIndex = 0;
        }

        public override void Save(ValuesDictionary valuesDictionary)
        {
            valuesDictionary.SetValue("CommandLine", m_commandLine);
        }

        public void Update(float dt)
        {
            //if (QuickMode && !HasCollidabled)
            //{
            //    CollidableBlocks = new bool[BlocksManager.Blocks.Length];
            //    for (int b = 0; b < BlocksManager.Blocks.Length; b++)
            //    {
            //        CollidableBlocks[b] = BlocksManager.Blocks[b].IsCollidable;
            //        BlocksManager.Blocks[b].IsCollidable = false;
            //    }
            //    HasCollidabled = true;
            //}
            //if (!QuickMode && HasCollidabled)
            //{
            //    for (int b = 0; b < CollidableBlocks.Length; b++)
            //    {
            //        BlocksManager.Blocks[b].IsCollidable = CollidableBlocks[b];
            //    }
            //    HasCollidabled = false;
            //}
            if (m_pointDataWidget == null && !string.IsNullOrEmpty(m_commandLine))
            {
                InitPointDataWidget();
            }
            if (m_subsystemCommand.m_componentPlayer != null)
            {
                m_subsystemCommand.m_componentPlayer.ComponentBody.TerrainCollidable = !QuickMode;
            }
            if (m_pointDataWidget != null && m_subsystemCommand.m_componentPlayer != null)
            {
                Vector2 vector = m_subsystemCommand.m_componentPlayer.GameWidget.ActualSize;
                m_subsystemCommand.m_componentPlayer.GameWidget.SetWidgetPosition(m_withdrawButton, new Vector2(vector.X - 180, 23));
                m_subsystemCommand.m_componentPlayer.GameWidget.SetWidgetPosition(m_recoveryButton, new Vector2(vector.X - 130, 23));
                bool isActiveRodBlock = (Terrain.ExtractContents(m_subsystemCommand.m_componentPlayer.ComponentMiner.ActiveBlockValue) == CmdRodBlock.Index);
                bool isActiveCommandWidget = m_subsystemCommand.m_componentPlayer.ComponentGui.ModalPanelWidget is CommandEditWidget;
                m_pointDataWidget.IsVisible = (QuickMode && isActiveRodBlock && !isActiveCommandWidget);
                m_withdrawButton.IsVisible = m_pointDataWidget.IsVisible;
                m_recoveryButton.IsVisible = m_pointDataWidget.IsVisible;
                if (m_pointDataWidget.IsVisible)
                {
                    if (m_withdrawButton.IsClicked)
                    {
                        if (WithdrawBlockManager.WithdrawMode)
                        {
                            WithdrawBlockManager.CarryOut(Project.FindSubsystem<SubsystemCommandDef>());
                        }
                        else
                        {
                            m_subsystemCommand.m_componentPlayer.ComponentGui.DisplaySmallMessage("请开启撤回模式", m_color, false, false);
                        }
                    }
                    if (m_recoveryButton.IsClicked)
                    {
                        if (WithdrawBlockManager.WithdrawMode)
                        {
                            WithdrawBlockManager.Recovery(Project.FindSubsystem<SubsystemCommandDef>());
                        }
                        else
                        {
                            m_subsystemCommand.m_componentPlayer.ComponentGui.DisplaySmallMessage("请开启撤回模式", m_color, false, false);
                        }
                    }
                    foreach (string p in m_commandPoints.Keys)
                    {
                        if (m_commandPoints[p].Button.IsClicked)
                        {
                            m_commandPoints[p].Lock = !m_commandPoints[p].Lock;
                            SetPointColor(p);
                            string tips = p.Replace("pos", "点") + (m_commandPoints[p].Lock ? "已锁定" : "已解锁");
                            m_subsystemCommand.m_componentPlayer.ComponentGui.DisplaySmallMessage(tips, Color.Yellow, false, false);
                        }
                    }
                }
            }
        }

        public void InitPointDataWidget()
        {
            if (m_pointDataWidget == null)
            {
                m_withdrawButton = new BitmapButtonWidget();
                m_withdrawButton.IsVisible = false;
                m_withdrawButton.Size = new Vector2(40, 40);
                m_withdrawButton.NormalSubtexture = new Subtexture(ContentManager.Get<Texture2D>("Textures/Withdraw1"), Vector2.Zero, Vector2.One);
                m_withdrawButton.ClickedSubtexture = new Subtexture(ContentManager.Get<Texture2D>("Textures/Withdraw2"), Vector2.Zero, Vector2.One);
                m_subsystemCommand.m_componentPlayer.GameWidget.Children.Add(m_withdrawButton);
                m_recoveryButton = new BitmapButtonWidget();
                m_recoveryButton.IsVisible = false;
                m_recoveryButton.Size = new Vector2(40, 40);
                m_recoveryButton.NormalSubtexture = new Subtexture(ContentManager.Get<Texture2D>("Textures/Withdraw3"), Vector2.Zero, Vector2.One);
                m_recoveryButton.ClickedSubtexture = new Subtexture(ContentManager.Get<Texture2D>("Textures/Withdraw4"), Vector2.Zero, Vector2.One);
                m_subsystemCommand.m_componentPlayer.GameWidget.Children.Add(m_recoveryButton);
                m_pointDataWidget = new StackPanelWidget();
                m_pointDataWidget.Name = "PointDataWidget";
                m_pointDataWidget.Direction = LayoutDirection.Vertical;
                m_subsystemCommand.m_componentPlayer.GameWidget.SetWidgetPosition(m_pointDataWidget, new Vector2(100, 20));
                m_pointDataWidget.IsHitTestVisible = false;
                m_pointDataWidget.ClampToBounds = true;
                m_pointDataWidget.IsVisible = false;
                m_subsystemCommand.m_componentPlayer.GameWidget.Children.Add(m_pointDataWidget);
            }
            m_pointDataWidget.Children.Clear();
            m_commandPoints.Clear();
            string[] kws = m_commandLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string k in kws)
            {
                if (k.StartsWith("pos"))
                {
                    string[] sp = k.Split(new char[] { ':' });
                    if (sp[0] == "pos") sp[0] = "pos1";
                    CommandPointData pointData = new CommandPointData();
                    pointData.Pos = sp[0];
                    pointData.Value = sp[1];
                    pointData.Lock = false;
                    m_commandPoints[pointData.Pos] = pointData;
                }
            }
            if (m_commandPoints.Count > 0)
            {
                if (m_pointIndex >= m_commandPoints.Count) m_pointIndex = m_commandPoints.Count - 1;
                foreach (string p in m_commandPoints.Keys)
                {
                    BevelledButtonWidget buttonWidget = new BevelledButtonWidget();
                    m_commandPoints[p].Button = buttonWidget;
                    buttonWidget.Name = p;
                    buttonWidget.Text = p.Replace("pos", "点") + ":" + m_commandPoints[p].Value;
                    buttonWidget.Size = new Vector2(200, 50);
                    buttonWidget.CenterColor = new Color(64, 64, 64, 32);
                    buttonWidget.BevelSize = 0.7f;
                    SetPointColor(p);
                    m_pointDataWidget.Children.Add(buttonWidget);
                    CanvasWidget canvasWidget = new CanvasWidget();
                    canvasWidget.Size = new Vector2(0, 5);
                    m_pointDataWidget.Children.Add(canvasWidget);
                }
                SetPointSize();
            }
        }

        public void SetPointData(Point3 point)
        {
            try
            {
                if (!QuickMode || m_commandPoints.Count == 0 || string.IsNullOrEmpty(m_commandLine)) return;
                if (m_recordPosition.HasValue && point == m_recordPosition)
                {
                    Time.QueueTimeDelayedExecution(Time.RealTime + 0.1f, delegate
                    {
                        CommandData commandData = new CommandData(Point3.Zero, m_commandLine);
                        commandData.TrySetValue();
                        m_subsystemCommand.Submit(commandData.Name, commandData, false);
                        m_subsystemCommand.m_componentPlayer.ComponentGui.DisplaySmallMessage(string.Format("已提交指令:{0}${1}", commandData.Name, commandData.Type), Color.Yellow, false, false);
                    });
                }
                else
                {
                    if (m_pointIndex >= m_commandPoints.Count) m_pointIndex = m_commandPoints.Count - 1;
                    foreach (string pk in m_commandPoints.Keys)
                    {
                        m_commandPoints[pk].Button.Color = m_commandPoints[pk].Lock ? Color.Red : Color.White;
                        m_commandPoints[pk].Button.BevelColor = m_commandPoints[pk].Button.Color;
                    }
                    bool LockAll = true;
                    foreach (string pk in m_commandPoints.Keys)
                    {
                        if (!m_commandPoints[pk].Lock)
                        {
                            LockAll = false;
                            break;
                        }
                    }
                    if (LockAll) return;
                    do
                    {
                        m_pointIndex = (m_pointIndex + 1) % m_commandPoints.Count;
                    }
                    while (m_commandPoints["pos" + (m_pointIndex + 1)].Lock);
                    string p = "pos" + (m_pointIndex + 1);
                    if (m_commandPoints.Count == 1)
                    {
                        m_commandLine = m_commandLine.Replace("pos:" + m_commandPoints[p].Value, "pos:" + point.ToString());
                    }
                    else
                    {
                        m_commandLine = m_commandLine.Replace(p + ":" + m_commandPoints[p].Value, p + ":" + point.ToString());
                    }
                    m_commandPoints[p].Value = point.ToString();
                    m_commandPoints[p].Button.Text = p.Replace("pos", "点") + ":" + point.ToString();
                    SetPointSize();
                    SetPointColor(p);
                }
            }
            catch (Exception e)
            {
                Log.Warning("DebugPoint:" + e.Message);
            }
        }

        public void SetPointColor(string p)
        {
            m_commandPoints[p].Button.Color = (p == "pos" + (m_pointIndex + 1)) ? Color.Green : Color.White;
            if (m_commandPoints[p].Lock) m_commandPoints[p].Button.Color = Color.Red;
            m_commandPoints[p].Button.BevelColor = m_commandPoints[p].Button.Color;
        }

        public void SetPointSize()
        {
            int maxSize = 0;
            foreach (string pk in m_commandPoints.Keys)
            {
                if (maxSize < m_commandPoints[pk].Button.Text.Length) maxSize = m_commandPoints[pk].Button.Text.Length;
            }
            foreach (string pk in m_commandPoints.Keys)
            {
                m_commandPoints[pk].Button.Size = new Vector2(maxSize * 13.3f, 50);
            }
        }
    }
}